﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NF_Tools
{
    public partial class BF_TransparentPicture :PictureBox
    {
        private Image default_ICO;

        [Category("WXP"), DisplayName("DisplayImage")]
        public Image Default_ICO
        {
            set
            {
                CreateControlRegion(this, new Bitmap(value));
                default_ICO = value;
            }
            get { return default_ICO; }
        }

        public BF_TransparentPicture()
        {
            InitializeComponent();
            this.Image = null;
        }

        public BF_TransparentPicture(IContainer container)
        {
            container.Add(this);
            InitializeComponent();
            this.Image = null;
        }



        //创建支持位图区域的控件
        public static void CreateControlRegion(Control control, Bitmap bitmap)
        {
            //设置控件大小为位图大小
            control.Width = bitmap.Width;           //设置窗体的宽度
            control.Height = bitmap.Height;         //设置窗体的高度
            PictureBox pic = (PictureBox)control;
            //将位图设为窗体背景
            pic.Image = bitmap;
            //计算位图中不隐藏部分的边界
            GraphicsPath graphicsPath = CalculateControlGraphicsPath(bitmap);
            //应用到新的区域
            pic.Region = new Region(graphicsPath);
        }

        private static GraphicsPath CalculateControlGraphicsPath(Bitmap bitmap)
        {
            //创建GraphicsPath对象
            GraphicsPath graphicsPath = new GraphicsPath();
            //得到左上角颜色
            Color colorTransparent = bitmap.GetPixel(0, 0);
            //找到第一个坐标x
            int colOpaquePixel = 0;
            //偏历所有行(Y方向)
            for (int row = 0; row < bitmap.Height; row++)
            {
                //重新指定colOpaquePixel的值
                colOpaquePixel = 0;
                //偏历所有列(X方向)
                for (int col = 0; col < bitmap.Width; col++)
                {
                    //如果是不需要透明处理的点则标记，然后继续偏历
                    if (bitmap.GetPixel(col, row) != colorTransparent)
                    {
                        //记录当前位置
                        colOpaquePixel = col;
                        //建立新变量来记录当前点
                        int colNext = col;
                        //从找到不透明的点开始，到透明点开始或到达图片宽度
                        for (colNext = colOpaquePixel; colNext < bitmap.Width; colNext++)
                            if (bitmap.GetPixel(colNext, row) == colorTransparent)
                                break;
                        //将不透明点加到GraphicsPath的AddRectangle()方法里
                        graphicsPath.AddRectangle(new Rectangle(colOpaquePixel, row, colNext - colOpaquePixel, 1));
                        col = colNext;
                    }
                }
            }
            return graphicsPath;
        }
    }
}
